apiready = function(){
seajs.use(['../../V',"../../api","../../jquery","../../app","../../service","../../swiper","../../dialog"],function(V,$api,$,app,service,Swiper,dialog){
	var vm = {
		el: '.container',
	  	data: {
	    	tabIndex: 0,
				shopInfo: {},
				goodsInfo: {},
				goodsId: '', // 商品ID
				goodsImages: [], // banner图片列表
				commentList: [], // 评论列表
				commentPage: 1, // 评论列表页数
				hasMoreComment: true, // 是否有更多评论
				isCollect: false, // 是否已经收藏
				collectId: '', // 收藏id
				number: 1, // 购买数量
				choicInfo: null, // 购买的商品
				isSeller: false, // 是否显示购买按钮
				shareShow: false, // 是否显示分享
				tipsInfo: {}, // 商城提示消息
				tipsList: [], // 商城提示列表
				tipsMsg: {}, // 提示内容
				otherUserInfo: {}, // 客服信息
				goodsOptions: [], // 规格信息列表
				chocOption: {}, // 选中的规格信息
				allStock: 0, // 商品总库存
				allCount: 0, // 总销售量
				userInfo: '', // 获取用户身份
				isSelectO: false, // 是否选择了型号
				isClickComment: false,
				template: '',
				bs: ""	//ajax弹出服务器提示控制变量
	  	},
			created: function(){
				var that = this;
				var goodsId = api.pageParam.goodsId;
				var isSeller = api.pageParam.isSeller;
				this.goodsId = goodsId;

				if (isSeller) {
					this.isSeller = true;
				}

				if($api.getStorage("user")){
					this.userInfo = $api.getStorage("user").data;
					this.bs = 1;
				}
				console.log(123);
				// 初始化
				this.init();

				// 触底
				api.addEventListener({
			 	    name: 'scrolltobottom',
						extra:{
				        threshold: 0
				    }
			 	}, function(ret, err){
						that.scrolltobottom()
			 	});

				// 前往购物车
				api.addEventListener({
				    name: 'toCart'
				}, function(ret, err){
				    if(ret){
				      app.openWin('buyCart');
				    }
				});

				// 前往商城首页或者我的名片
				api.addEventListener({
				    name: 'shopDetailDoShomeThing'
				}, function(ret, err){
				    if(ret){
				      var type = ret.value.type;
							if (type == 0) {
								// 商城首页
								api.openWin({
										name: 'index',
										// customRefreshHeader: "UIPullRefreshMotive",
										url: 'widget://src/Shop/shop_index/shop_index.html',
										pageParam: {
												channel: 'YK'
										}
								})
							}
							// else if (type == 1) {
							// 	// 我的名片
							// 	api.closeToWin({
							// 	    name: 'root',
							// 			animation: {
							// 				type: 'fade',
							// 				subType: 'from_right',
							// 				duration: 300
							// 			}
							// 	});
							// }
				    }
				});

	  	},
	  	methods:{
				init: function () {
					var that = this;
					// 获取商品信息
					this.getGoodsDetail(function () {
						// 添加足迹
						that.addUserStep();

						// 获取提示消息
						that.getGoodsInformation(0);
					});

					$api.setTimeout(function(){
						var mySwiper = new Swiper('.swiper-container', {
							pagination: {
						    el: '.swiper-pagination',
								type: 'fraction'
						  },
						})
					},900);
				},

				// 显示分享
				showShare: function () {
					this.shareShow = true;
				},
				hideShare: function () {
					this.shareShow = false;
				},

				// 获取商城提示消息
				getGoodsInformation: function (time_stamp) {
					var that = this;
					app.ajax(
						service['getGoodsInformation'],
						{
							data: {
								values: {
									unionid: $api.getStorage("shop_unionid"),
									time_stamp: time_stamp,
									goods_id: that.goodsId,
									mask: 'none',
									bs: this.bs
								}
							}
						},
						function (res) {
							if (res.code == 0) {
								that.tipsInfo = res.data;
								that.tipsList = res.data.list;
								that.showTips();
							} else {
								// api.toast({
								//     msg: res.message,
								//     duration: 2000,
								//     location: 'bottom'
								// });
							}
						}
					);
				},

				// 显示提示
				showTips: function () {
					var that = this;
					if (this.tipsList.length > 1) {
						this.tipsMsg = {
							avater: that.tipsList[0].avater,
							name: that.tipsList[0].nickname,
							msg: that.tipsList[0].msg,
							goodsId: that.tipsList[0].goods_id,
							groupId: that.tipsList[0].group_id
						};
						this.tipsList = this.tipsList.splice(0,1);
						$('.loop-tips').fadeIn('fast',function () {
							$(this).css('display','flex');
						});
						$api.setTimeout(function () {
							$('.loop-tips').fadeOut();
							that.showTips();
						}, 3000);
					} else {
						$api.setTimeout(function () {
							that.getGoodsInformation(that.tipsInfo.time_stamp);
						}, 5000);
					}
				},

				// 分享到微信
				shareToWx: function (type) {
					var that = this;
					if (this.bs == "") { //游客模式，没有缓存
							dialog.alert({
									title: '游客模式',
									msg: '体验更多功能，请先登录',
									buttons: ['取消', '确定']
							}, function(ret) {
									if (ret.buttonIndex == 2) { //确认
											api.closeToWin({
													name: 'WeChat_login'
											});
									}
							})
					}else{
						var wx = api.require('wx');
						var toWhere;
						if (type == 1) {
							// 分享给朋友
							toWhere = 'session';
						} else if (type == 2) {
							// 分享到朋友圈
							toWhere = 'timeline';
						}
						app.downloadImg(that.goodsInfo.cover, function (img_url) {
							that.getShareLink(function(url) {
								wx.shareWebpage({
								    scene: toWhere,
										title: that.goodsInfo.name,
										description: that.chocOption.name,
								    contentUrl: url,
										thumb: img_url
								}, function(ret, err) {
								    if (ret.status) {
								        api.toast({
								            msg: '分享成功',
								            duration: 2000,
								            location: 'bottom'
								        });
								    } else {
											api.toast({
													msg: '分享失败',
													duration: 2000,
													location: 'bottom'
											});
								    }
								});
							});
						});
					}

				},

				// 获取分享连接
				getShareLink: function (callback) {
					var that = this;
					app.ajax(
						service['Share'],
						{
							data: {
								values: {
									type: 2,
									unionid: $api.getStorage("shop_unionid"),
									share_id: that.goodsId,
									is_yzc: 1
								}
							}
						},
						function (res) {
							if (res.code == 0) {
								var url = res.data;
								callback(url);
							} else {
								api.toast({
								    msg: '获取分享链接失败',
								    duration: 2000,
								    location: 'bottom'
								});
							}
						}
					);
				},

				// 获取商品详情
				getGoodsDetail: function (cb) {
					var that = this;
					app.ajax(
						service['yzcDetail'],
						{
							data: {
								values: {
									goods_id: that.goodsId,
									customer_unionid: $api.getStorage("shop_unionid"),
									bs: this.bs
								}
							}
						},
						function (res) {
							if (res.code == 0) {
								that.goodsInfo = res.data;
								that.shopInfo = res.data.shop;
								that.template = res.data.template;	//运费模版
								that.goodsImages = res.data.goods_images; // banner图片列表
								that.otherUserInfo = res.data.exchange;  // 店主信息
								that.goodsOptions = res.data.goods_options;
								that.chocOption = res.data.goods_options[0];
								that.allStock = res.data.shop.all_stock; // 商品总库存
								that.allCount = res.data.shop.all_count; // 已出售总数

								// 检测是否收藏
								if (!res.data.collect_id) {
									that.isCollect = false;
								} else {
									that.isCollect = true;
									that.collectId = res.data.collect_id;
								}

								cb();
							} else {
								// api.toast({
								// 		msg: res.message,
								// 		duration: 2000,
								// 		location: 'bottom'
								// });
							}
						}
					);
				},

				// 查看大图
				showBigImg: function (index) {
					var that = this;
					var photoBrowser = api.require('photoBrowser');
					var urlArr = [];
					for (var i = 0; i < that.goodsImages.length; i++) {
						urlArr.push(that.goodsImages[i].url);
					}

					photoBrowser.open({
					    images: urlArr,
					    bgColor: '#000',
							activeIndex: index
					}, function(ret, err) {
					    if (ret.eventType == 'click') {
					      photoBrowser.close();
					    }
					});
				},

				// 添加我的足迹
				addUserStep: function () {
					var that = this;
					app.ajax(
						service['addUserStep'],
						{
							data: {
								values: {
									goods_id: that.goodsId,
									unionid: $api.getStorage("shop_unionid"),
									bs: this.bs
								}
							}
						},
						function (res) {
							if (res.code != 0 && this.bs) {
								api.toast({
								    msg: '添加足迹失败',
								    duration: 2000,
								    location: 'bottom'
								});
							}
						}
					);
				},

				// 获取评论列表
				getComment: function () {
					var that = this;
					var page = this.commentPage;
					app.ajax(
						service['getGoodsComment'],
						{
							data: {
								values: {
									goods_id: that.goodsId,
									shop_code: that.shopInfo.shop_code,
									page: page
								}
							}
						},
						function (res) {
							if (res.code == 0) {
								if (that.commentPage == 1) {
									that.commentList = res.data;
								} else {
									if (res.data.length > 0) {
										for (var i = 0, len = res.data.length; i < len; i++) {
											that.commentList.push(res.data[i]);
										}
										that.hasMoreComment = true;
									} else {
										that.hasMoreComment = false;
									}
								}
							} else {
								api.toast({
										msg: res.message,
										duration: 2000,
										location: 'bottom'
								});
							}
						}
					);
				},

				// 收藏、取消收藏
				favorGoods: function () {
					var that = this;
					var isCollect = that.isCollect;

					var url,arg;
					if (this.bs == "") { //游客模式，没有缓存
							dialog.alert({
									title: '游客模式',
									msg: '体验更多功能，请先登录',
									buttons: ['取消', '确定']
							}, function(ret) {
									if (ret.buttonIndex == 2) { //确认
											api.closeToWin({
													name: 'WeChat_login'
											});
									}
							})
					}else{
						if (isCollect) {
							// 取消收藏
							url = service['cancelCollectShop'];
							arg = {
								unionid: $api.getStorage("shop_unionid"),
								favorite_id: that.collectId
							}
						} else {
							// 添加收藏
							url = service['addToFavoriteShop'];
							arg = {
								unionid: $api.getStorage("shop_unionid"),
								type: 1,
								goods_id: that.goodsId
							}
						}

						app.ajax(
							url,
							{
								data: {
									values: arg
								}
							},
							function (res) {
								if (res.code == 0) {
									if (!isCollect) {
										if (res.data) {
											that.collectId = res.data;
										}
									}
									that.isCollect = !that.isCollect;
								} else {
									api.toast({
											msg: res.message,
											duration: 2000,
											location: 'bottom'
									});
								}
							}
						);
					}

				},

				// 选择商品型号\规格
				selectOption: function (name, id, price, stock, optionId, index) {
					var def_obj = {
						price: price,
						stock: stock,
						name: name,
						goods_id: id,
						option_id: optionId
					};
					this.isSelectO = true;

					this.number = 1;
					for (var i = 0, len = $('.list-item-js').length; i < len; i++) {
						$('.list-item-js').eq(i).css({'color': '#000'});
					}
					$('.list-item-js').eq(index).css({'color': 'red'});

					this.choicInfo = def_obj;
					this.chocOption = this.goodsOptions[index];
				},

				// 购买数量
				goodsNum: function (type) {
					if (type == 'add') {
						// 添加
						if (this.number < this.chocOption.stock) {
							var num = parseInt(this.number);
							num += 1;
							this.number = num;
						}
					} else if (type == 'reduce') {
						// 减少
						if (this.number >= 2) {
							var num = parseInt(this.number);
							num -= 1;
							this.number = num;
						}
					}
				},

				// 立即购买
				buyNow: function () {
					var that = this;

					if (this.bs == "") { //游客模式，没有缓存
							dialog.alert({
									title: '游客模式',
									msg: '体验更多功能，请先登录',
									buttons: ['取消', '确定']
							}, function(ret) {
									if (ret.buttonIndex == 2) { //确认
											api.closeToWin({
													name: 'WeChat_login'
											});
									}
							})
					}else{
						if (!that.choicInfo) {
							this.goodsType(); // 选择型号规格
							api.toast({
							    msg: '请选择商品型号',
							    duration: 2000,
							    location: 'bottom'
							});
							return;
						}
						var quantity = $('.number-goods').val(); // 数量
						var optionId = that.choicInfo.option_id; // 规格
						var str = optionId + ',' + quantity;
						var count = this.choicInfo.stock;
						if (quantity > count) {
							api.toast({
							    msg: '库存不足',
							    duration: 2000,
							    location: 'bottom'
							});
							return;
						}

						app.openWin('shopIndexYzcOrder', {options: str}); // 生成订单
						this.$refs.goodsTypeDetail.classList.remove("active");
						that.choicInfo = null;
						for (var i = 0, len = $('.list-item-js').length; i < len; i++) {
							$('.list-item-js').eq(i).css({'color': '#000'});
						}
					}

				},

				// 触底
				scrolltobottom: function () {
					if (this.tabIndex == 1) {
						if (this.hasMoreComment) {
							this.commentPage += 1;
							this.getComment();
						}
					}
				},

				// 联系客服
				toChar: function () {
					var that = this;
					var obj = {
						openid: that.otherUserInfo.openid, //id
						nickname: that.shopInfo.shop_name, //昵称
						src: that.shopInfo.shop_logo, //头像
						new_nickname: that.otherUserInfo.new_nickname, //对象
					}
					if (this.bs == "") { //游客模式，没有缓存
							dialog.alert({
									title: '游客模式',
									msg: '体验更多功能，请先登录',
									buttons: ['取消', '确定']
							}, function(ret) {
									if (ret.buttonIndex == 2) { //确认
											api.closeToWin({
													name: 'WeChat_login'
											});
									}
							})
					}else{
						app.yz_chat(obj);
					}

				},

				// 前往店铺首页
				toShop: function () {
					var shopData = this.shopInfo;
					var otherUserId = this.shopInfo.out_user_id;
					app.openWin('buyMain', {shopData: shopData, otherUserInfoId: otherUserId});
				},

				// 前往其他商品
				toOtherGoods: function (id,group_booking) {
					if (group_booking) {
						url = '../../buy_group_goods/group_goods.html';
					} else {
						url = '../buy_goods/goods.html';
					}
					api.openFrame({
					    name: 'otherGoods',
					    url: url,
					    rect: {
					        x: 0,
					        y: 0,
					        w: 'auto',
					        h: 'auto'
					    },
					    pageParam: {
					        goodsId: id
					    },
							reload: true
					});
				},


	  		//--服务
	  		goodsServer: function(et){
	  			this.$refs.goodsServeDetail.classList.add("active");
	  		},
	  		//--服务详细
	  		goodsServeDetailBg: function(et){
	  			this.$refs.goodsServeDetail.classList.remove("active");
	  		},
				//--运费模版弹框显示
	  		goodsDispatch: function(et){
	  			this.$refs.goodsDispatchDetail.classList.add("active");
	  		},
	  		//--运费模版弹框隐藏
	  		goodsDispatchDetailBg: function(et){
	  			this.$refs.goodsDispatchDetail.classList.remove("active");
	  		},
	  		//--选择类型
	  		goodsType: function(et){
	  			this.$refs.goodsTypeDetail.classList.add("active");
	  		},
	  		//--选择类型详细
	  		goodsTypeDetailBg: function(et){
	  			this.$refs.goodsTypeDetail.classList.remove("active");
	  		},
	  		//--评价与详情
	  		goodsDetailTab: function(et){
					this.commentPage = 1;
	  			var list = this.$refs.goodsDetailList.children;
	  			var index = + et.target.dataset.index;
	  			for(var i=0; i < list.length; i++){
	  				list[i].classList.remove("active");
	  			}
	  			this.tabIndex = index;
	  			list[index].classList.add("active");

					if (et.target.dataset.index == 1) {
						// 获取商品评论
						if (!this.isClickComment) {
							this.isClickComment = true;
							this.getComment();
						}

					}
	  		},
				showGoodsyon: function () {
					this.$refs.goodsyon.classList.add("active");
				},
				goodsyonBg: function () {
					this.$refs.goodsyon.classList.remove("active");
				},
				showBigImgs: function (url) {
					var photoBrowser = api.require('photoBrowser');
					var urlArr = [url];
					photoBrowser.open({
							images: urlArr,
							bgColor: '#000',
							activeIndex: 0
					}, function(ret, err) {
							if (ret.eventType == 'click') {
								photoBrowser.close();
							}
					});
				}

	  	},
			computed: {
				// 获取所在地省级地址
				locationChange: function () {
					return this.shopInfo.shop_location.split(' ')[1];
				},

				// 获取最低出售价
				getLowPrice: function () {
					var option = this.goodsOptions;
					if (option.length < 2) {
						return this.chocOption.yzc;
					} else {
						var price = option[0].yzc;
						for (var i = 0, len = option.length; i < len; i++) {
							if (price > option[i].yzc) {
								price = option[i].yzc;
							}
						}
						return price;
					}
				}
			},
	  	mounted:function() {
	  		var self = this;
			// vue执行完毕后
			//--z支付返回刷新
			api.addEventListener({
				name: 'payBackGoods_'
			},function(ret,val){
				self.init();
			});
	  	}
	};
	var even =function () {
		$('.buy-head-cart').on('click', function () {
			api.sendEvent({
			    name: 'toCart'
			});
		});
		$('.buy-head-nav').on('click', function () {
			$('.nav-dio-top').toggle();
		});

		$('.nav-dio-top div').on('click', function () {
			var type = $(this).index();

			api.sendEvent({
					name: 'shopDetailDoShomeThing',
					extra: {
							type: type,
					}
			});
		});
	}
	var newVue = new Vue(vm);
	even();
});
}
